from django.db import models
from django.contrib.auth.models import User

class CredentialCategory(models.Model):
    name = models.CharField(max_length=100, verbose_name="分类名称")
    description = models.TextField(blank=True, verbose_name="分类描述")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "凭证分类"
        verbose_name_plural = "凭证分类"
    
    def __str__(self):
        return self.name

class Credential(models.Model):
    STATUS_CHOICES = [
        ('normal', '系统正常'),
        ('unreachable', '网址打不开'),
        ('abandoned', '基本废弃'),
        ('warning', '警告'),
    ]
    
    category = models.ForeignKey(CredentialCategory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="分类")
    location = models.CharField(max_length=100, verbose_name="位置")
    device_name = models.CharField(max_length=200, verbose_name="设备名称")
    username = models.CharField(max_length=200, verbose_name="用户名")
    password = models.CharField(max_length=500, verbose_name="密码")
    url = models.URLField(max_length=500, blank=True, verbose_name="访问地址")
    protocol = models.CharField(max_length=50, blank=True, verbose_name="协议类型")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='normal', verbose_name="状态")
    notes = models.TextField(blank=True, verbose_name="备注")
    source_file = models.CharField(max_length=500, blank=True, verbose_name="来源文件")
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "账号密码凭证"
        verbose_name_plural = "账号密码凭证"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.location} - {self.device_name}"

class CredentialImportLog(models.Model):
    file_name = models.CharField(max_length=500, verbose_name="文件名")
    file_path = models.CharField(max_length=1000, blank=True, verbose_name="文件路径")
    total_count = models.IntegerField(default=0, verbose_name="总记录数")
    success_count = models.IntegerField(default=0, verbose_name="成功导入数")
    import_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="导入人")
    import_time = models.DateTimeField(auto_now_add=True, verbose_name="导入时间")
    parse_result = models.JSONField(default=dict, verbose_name="解析结果")
    
    class Meta:
        verbose_name = "凭证导入日志"
        verbose_name_plural = "凭证导入日志"
        ordering = ['-import_time']
    
    def __str__(self):
        return f"{self.file_name} - {self.import_time}"